<script setup lang="ts">
import {
  getUserList,
  downLoad,
  postUserDelete,
  resetPassword,
} from "@/services/userApi.ts";
import { onMounted, reactive, ref, computed } from "vue";
import type { UserListType } from "@/types/UserType.ts";
import { tableBorder } from "@/utils/border/table-border.ts";
import UserForm from "@/pages/system/User/user-form.vue";
import { Message, PaginationProps } from "@arco-design/web-vue";
import type { MenuListResType } from "@/types/MenuType.ts";
import { userUpload } from "@/services/commonApi";
import { downloadFile, getAvatar, windowURL } from "@/utils";
import useModal from "@/hooks/useModal.ts";
import Local from "@/utils/local";
import { shouldShowOperateColumn } from "@/directives/showColumn";
const { ModalShow, ModalHide } = useModal();


const data = ref<UserListType[]>([]);

const userForm = ref<{
  show: () => void;
  edit: (data: UserListType) => void;
}>();

const pagination = reactive<PaginationProps>({
  total: 0,
  current: 1,
  showTotal: true,
  pageSize: 10,
});

const formSearch = reactive({
  current: 1,
  username: "",
  phone: "",
  size: 10,
  realname: "",
});

function queryData() {
  // data.value = [];
  getUserList(formSearch).then((res) => {
    if (res.code === 200) {
      data.value = res.data.records;
      pagination.total = res.data.total;
      pagination.current = res.data.current;
      pagination.pageSize = res.data.size;
    }
  });
}

const handleAdd = () => {
  userForm.value?.show();
};

const handleEdit = (row: UserListType) => {
  userForm.value?.edit(row);
};

// 删除
const handleDelete = (row: UserListType) => {
  ModalShow({
    content: "您确认要删除当前用户吗？",
  }).then(() => {
    postUserDelete(row.id).then((res) => {
      if (res.code === 200) {
        if (data.value.length === 1) {
          formSearch.current = formSearch.current - 1;
        }
        queryData();
        ModalHide();
        Message.success(res.data);
      } else {
        ModalHide();
      }
    });
  });
};

const handlePageChange = (page: number) => {
  formSearch.current = page;
  queryData();
};

onMounted(() => {
  queryData();
});

const columns = [
  {
    title: "序号",
    dataIndex: "index",
    align: "center",
    width: 80,
    slotName: "index",
  },
  {
    title: "用户账号",
    dataIndex: "username",
    width: 180,
    align: "center",
  },
  {
    title: "用户姓名",
    dataIndex: "realname",
    width: 180,
    align: "center",
  },
  {
    title: "头像",
    dataIndex: "avatar",
    slotName: "avatar",
    width: 80,
    align: "center",
  },
  {
    title: "性别",
    dataIndex: "sex",
    slotName: "sex",
    width: 80,
    align: "center",
  },
  {
    title: "生日",
    dataIndex: "birthday",
    width: 200,
    align: "center",
  },
  {
    title: "手机号",
    dataIndex: "phone",
    width: 140,
    align: "center",
  },
  {
    title: "邮箱",
    dataIndex: "email",
    minWidth: 200,
  },
  {
    title: "状态",
    slotName: "status",
    width: 80,
    align: "center",
  },
];

const dynamicColumns = computed(() => {
 /* if (shouldShowOperateColumn(["edit", "delete", "reset"], 3)) {

    return [
      ...columns,
      {
        title: "操作",
        slotName: "operate",
        align: "center",
        width: 160,
      },
    ];
  } else {
    return columns;
  }*/
  return [
    ...columns,
    {
      title: "操作",
      slotName: "operate",
      align: "center",
      width: 160,
    },
  ];
});

function getSexString(sex: 0 | 1 | null) {
  if (sex === 0) {
    return "女";
  }
  if (sex === 1) {
    return "男";
  }
  return "";
}

function getStatusString(status: 0 | 1 | null) {
  if (status === 1) {
    return "禁用";
  }
  if (status === 0) {
    return "正常";
  }
  if (status === null) {
    return "暂无";
  }
}

const getColor = (status: 0 | 1 | null) => {
  // 根据状态返回不同的type
  switch (status) {
    case 1:
      return "#f53f3f";
    case 0:
      return "#00b42a";
  }
};

const exportToExcel = () => {
  userUpload(formSearch).then((res: any) => {
    downloadFile(res, `用户管理.xlsx`);
  });
};

// 下载导入模版
const dowmLoad = () => {
  downLoad({ templateName: "userTemplate" }).then((res) => {
    downloadFile(res as Blob, `用户导入模版.xlsx`);
  });
};

// 重置密码
const handleReset = (row: UserListType) => {
  ModalShow({
    content: "是否重置当前用户密码？",
  }).then(() => {
    resetPassword(row.id).then((res) => {
      if (res.code === 200) {
        if (data.value.length === 1) {
          formSearch.current = formSearch.current - 1;
        }
        queryData();
        ModalHide();
        Message.success(res.data);
      } else {
        ModalHide();
      }
    });
  });
};

const reset = () => {
  formSearch.username = "";
  formSearch.phone = "";
  formSearch.realname = "";
  search();
};

const search = () => {
  formSearch.current = 1;
  queryData();
};

const handleSelect = (e: string, row: MenuListResType) => {
  if (e === "删除") {
    handleDelete(row);
  }
  if (e === "重置密码") {
    handleReset(row);
  }
};
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-form
        label-align="left"
        auto-label-width
      >
        <a-row :gutter="24">
          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-form-item label="用户账号">
              <a-input
                placeholder="请输入用户账号"
                allow-clear
                v-model="formSearch.username"
              />
            </a-form-item>
          </a-col>

          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-form-item label="用户姓名">
              <a-input
                placeholder="请输入用户姓名"
                allow-clear
                v-model="formSearch.realname"
              />
            </a-form-item>
          </a-col>

          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-form-item label="手机号">
              <a-input
                placeholder="请输入手机号"
                allow-clear
                v-model="formSearch.phone"
              />
            </a-form-item>
          </a-col>

          <a-col
            :xs="24"
            :sm="24"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
          >
            <a-space>
              <a-button
                type="primary"
                @click="search"
              >
                <template #icon>
                  <icon-search />
                </template>
                <span>查询</span>
              </a-button>
              <a-button @click="reset">
                <template #icon>
                  <icon-refresh />
                </template>
                <span>重置</span>
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card>
      <div class="tabletools">
        <a-space>
          <a-button
            type="primary"
            @click="handleAdd"
            v-has="'add'"
          >
            <template #icon>
              <icon-plus />
            </template>
            <span>新增</span>
          </a-button>
          <a-button
            type="primary"
            status="success"
            @click="exportToExcel"
            v-has="'export'"
          >
            <template #icon>
              <icon-share-external />
            </template>
            <span>导出</span>
          </a-button>
          <a-button
            type="primary"
            status="warning"
            @click="dowmLoad"
            v-has="'download'"
          >
            <template #icon>
              <icon-download />
            </template>
            下载导入模版
          </a-button>
          <ExcelUpload
            actions="sys/user/importXls"
            @success="queryData"
            v-has="'import'"
          >导入</ExcelUpload>
        </a-space>
      </div>

      <a-table
        style="user-select: none;"
        :data="data"
        :columns="dynamicColumns"
        :bordered="tableBorder"
        :pagination="pagination"
        @page-change="handlePageChange"
      >
        <template #index="{rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>
        <template #avatar="{ record }">
          <img
            style="width: 50px; height: 50px"
            :src="windowURL() + record.avatar"
            alt=""
          >
        </template>
        <template #sex="{ record }">
          {{getSexString(record.sex)}}
        </template>
        <template #status="{ record }">
          <a-tag :color="getColor(record.status)">{{ getStatusString(record.status) }}</a-tag>
        </template>
        <template #operate="{ record }">
          <a-space>
            <a-button
              type="primary"
              @click="handleEdit(record)"
              v-has="'edit'"
            >编辑</a-button>

            <a-dropdown @select="(e: string) => handleSelect(e, record)">
              <a-button
                type="primary"
                status="warning"
                v-more="{
                  list: ['delete', 'reset'],
                  len: 2
                }"
              >
                <span>更多</span>
                <icon-down />
              </a-button>
              <template #content>
                <a-doption v-has="'delete'">删除</a-doption>
                <a-doption v-has="'reset'">重置密码</a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <user-form
      ref="userForm"
      @list="queryData"
    />
  </a-space>
</template>

<style scoped lang="scss">
</style>